<template>
  <div class="add-metric-container">
    <el-form ref="form" :model="metricForm" :rules="rules" label-width="100px" style="width:95%;">
      <h2 style="text-align: left;margin-left:3.5%; ">已有Metric管理</h2>
      <el-row :gutter="2">
        <el-col :span="6">
          <el-form-item label="metric" prop="metric">
            <el-select v-model="metric" style="width:100%">
              <el-option v-for="item in metricArr" :key="item" :value="item" :label="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="querymetric">查询</el-button>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="metricRename">
            <el-input v-model="metricRename" placeholder="输入新metric名" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="renamemetric">重命名</el-button>
        </el-col>
        <el-col :span="3">
          <el-button style="float: right" type="danger" @click="delmetric">删除</el-button>
        </el-col>
      </el-row>
      <h2 style="text-align: left;margin-left:3.5%; ">Metric创建和修改</h2>
      <el-row :gutter="2">
        <el-col :span="6">
          <!-- <el-form-item label="Metric" prop="metricname">
            <el-input v-model="metricForm.metricname" clearable />
          </el-form-item> -->
          <el-form-item label="metric" prop="metricname">
            <el-select
              v-model="metricForm.metricname"
              style="width:100%"
              placeholder="输入或选择metric"
              filterable
              allow-create
              default-first-option
              @change="metricchange"
            >
              <el-option v-for="item in metricArr" :key="item" :value="item" :label="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-tooltip v-if="createMetricButton" class="item" effect="dark" content="创建无标签的Metric" placement="top-start">
            <el-button type="primary" @click="createNullMetric">创建</el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row v-for="(tag, i) in metricForm.taglist" :key="i" :gutter="0">
        <label class="el-form-item__label" style="width: 100px;font-weight: 700;" @click="deltagkey(i)">标签{{ i+1 }}<i class="el-icon-delete el-icon--right" /></label>
        <el-col :span="3">
          <el-input
            v-model="tag.tagname"
            placeholder="请输入键"
            clearable
          />
        </el-col>
        <label class="el-form-item__label" style="width: 60px;font-weight: 700;">标签值</label>
        <el-button
          v-for="(tagvalue, index) in tag.tagvaluelist"
          :key="index"
          :span="3"
          type="primary"
          plain
          style="margin-left: 0px;"
          @click="deltagvalue(i,index)"
        >{{ tagvalue }}<i class="el-icon-delete el-icon--right" />
        </el-button>
        <el-input
          v-model="tag.tagtempvalue"
          placeholder="请输入值"
          style="width:170px"
          clearable
          @change="addtagvalue(i)"
        />
        <el-button type="success" style="width:40px;padding:12px" @click="addtagvalue(i)">+</el-button>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="6">
          <el-button type="success" style="margin-left:100px" @click="addtag">添加标签</el-button>
        </el-col>
        <!-- <el-col :span="15">
          <el-button style="float: right" type="primary" @click="submitAdd">创建Metric</el-button>
        </el-col> -->
      </el-row>
    </el-form>
    <el-dialog v-if="queryDialogVisible" width="70%" :visible.sync="queryDialogVisible">
      <el-table :data="dialogdata" style="width: 100%">
        <el-table-column
          fixed
          prop="tag"
          label="标签"
          width="180"
        />
        <el-table-column label="标签值">
          <template slot-scope="scope">
            <span v-for="value in scope.row.valuelist" :key="value">{{ value }}&nbsp;</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
// import { getMetricList, getmetricNameList, addmetric } from '@/api/metric.js'
// import axios from 'axios'
import axiosservice from '@/utils/CommonData.js'
// import { getMetricsState, getMetricsLocal, setMetrics } from '@/utils/CommonData.js'

export default {
  name: 'MetricSetting',
  data() {
    return {
      createMetricButton: false,
      dialogdata: null,
      metrictagstree: null,
      queryDialogVisible: false,
      metricArr: [],
      metric: '',
      metricRename: '',
      metricForm: {
        metricname: '',
        taglist: [{
          tagname: 'equipment',
          tagtempvalue: '',
          tagvaluelist: []
        }]
      },
      rules: {
        metricname: [{ required: true, message: '请输入Metric' }]
      }
    }
  },
  created() {
    const _this = this
    window.delTag = _this.delTag
  },
  mounted() {
    this.getMetricTagTree()
  },
  methods: {
    addtagvalue(i) {
      if (this.metricForm.taglist[i].tagtempvalue && this.metricForm.metricname) { // 去空值
        if (this.metricForm.taglist[i].tagvaluelist.indexOf(this.metricForm.taglist[i].tagtempvalue) == -1) { // 去重复值
          axiosservice.get('/buildmetrictagstree?method=create&metric=' + this.metricForm.metricname + '&tags=' + this.metricForm.taglist[i].tagname + ':' + this.metricForm.taglist[i].tagtempvalue)
            .then((res) => {
              if (res.status == 200) {
                // this.metricNameArr = res.data.data.metricname
                if (res.data.code == 200) {
                  this.metricForm.taglist[i].tagvaluelist.push(this.metricForm.taglist[i].tagtempvalue)
                  this.$message('添加成功!')
                  this.createMetricButton = false
                  this.getMetricTagTree() // 更新MetricTagTree
                }
              }
            })
            .catch((error) => {
              console.log(error)
              this.getMetricTagTree() // 更新MetricTagTree
              this.$message.error('添加Metric失败!' + error)
            })
        }
      }
    },
    deltagvalue(i, j) {
      axiosservice.get('/deletetagv?method=deletetagv&metric=' + this.metricForm.metricname + '&tags=' + this.metricForm.taglist[i].tagname + ':' + this.metricForm.taglist[i].tagvaluelist[j])
        .then((res) => {
          if (res.status == 200) {
            // this.metricNameArr = res.data.data.metricname
            if (res.data.code == 200) {
              this.metricForm.taglist[i].tagvaluelist.splice(j, 1)
              this.getMetricTagTree() // 更新MetricTagTree
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.getMetricTagTree() // 更新MetricTagTree
          this.$message.error('添加Metric失败!' + error)
        })
      // this.metricForm.taglist[i].tagvaluelist.splice(j, 1)
    },
    deltagkey(i) {
      axiosservice.get('/deletetagk?method=deletetagk&metric=' + this.metricForm.metricname + '&tagk=' + this.metricForm.taglist[i].tagname)
        .then((res) => {
          if (res.status == 200) {
            // this.metricNameArr = res.data.data.metricname
            if (res.data.code == 200) {
              this.metricForm.taglist.splice(i, 1)
              this.getMetricTagTree() // 更新MetricTagTree
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.getMetricTagTree() // 更新MetricTagTree
          this.$message.error('添加Metric失败!' + error)
        })
      // this.metricForm.taglist[i].tagvaluelist.splice(j, 1)
    },
    addtag() {
      this.metricForm.taglist.push({
        tagname: '',
        tagtempvalue: '',
        tagvaluelist: []
      })
    },
    deltag(i) {
      this.metricForm.taglist.splice(i, 1)
    },
    getMetricTagTree() {
      axiosservice({
        url: '/metrictagstree',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            if (res.data.code == 200) {
              this.metrictagstree = JSON.parse(res.data.data)
              console.log('metrictagstree', this.metrictagstree)
              this.metricArr = []
              for (var p1 in this.metrictagstree) {
                this.metricArr.push(p1)
              }
              if (this.metricArr.length > 0) {
                this.metric = this.metricArr[0] // 默认值取第一个
              }
              console.log('metricArr', this.metricArr)
            }
            // setMetrics(res.data)
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取metrics数据失败!')
        })
    },
    metricchange(currentMetric) {
      if (currentMetric in this.metrictagstree) {
        this.createMetricButton = false
        console.log(currentMetric, this.metrictagstree[currentMetric])
        this.metricForm.taglist = []
        for (var tagk in this.metrictagstree[currentMetric]) {
          this.metricForm.taglist.push({
            tagname: tagk,
            tagtempvalue: '',
            tagvaluelist: [...this.metrictagstree[currentMetric][tagk]]
          })
        }
      } else {
        console.log(currentMetric)
        this.createMetricButton = true
        this.metricForm.taglist = [{
          tagname: 'equipment',
          tagtempvalue: '',
          tagvaluelist: []
        }]
      }
    },
    createNullMetric() {
      axiosservice.get('/buildmetrictagstree?method=create&metric=' + this.metricForm.metricname)
        .then((res) => {
          if (res.status == 200) {
            // this.metricNameArr = res.data.data.metricname
            if (res.data.code == 200) {
              this.$message('创建Metric成功!')
              this.createMetricButton = false
              this.getMetricTagTree() // 更新MetricTagTree
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.getMetricTagTree() // 更新MetricTagTree
          this.$message.error('添加Metric失败!' + error)
        })
    },
    querymetric() {
      this.dialogdata = []
      for (var tagk in this.metrictagstree[this.metric]) {
        this.dialogdata.push({
          tag: tagk,
          valuelist: this.metrictagstree[this.metric][tagk]
        })
      }
      this.queryDialogVisible = true
    },
    addmetric(tagslist) {
      let successnum = 0
      for (const tagkv of tagslist) {
        axiosservice.get('/buildmetrictagstree?method=create&metric=' + this.metricForm.metricname + '&tags=' + tagkv)
          .then((res) => {
            if (res.status == 200) {
            // this.metricNameArr = res.data.data.metricname
              if (res.data.code == 200) {
                successnum += 1
                console.log(successnum, tagslist.length)
                console.log(tagkv, tagslist[tagslist.length - 1])
              }
            }
            if (tagkv == tagslist[tagslist.length - 1]) {
              if (successnum == tagslist.length) {
                this.$message('添加成功!')
                this.getMetricTagTree() // 更新MetricTagTree
              } else {
                this.$message.error('未能全部添加，成功条数：' + successnum)
                console.log('成功', successnum)
              }
            }
          })
          .catch((error) => {
            console.log(error)
            this.getMetricTagTree() // 更新MetricTagTree
            this.$message.error('添加Metric失败!' + error)
          })
      }
    },
    renamemetric() {
      axiosservice.get('/buildmetrictagstree?method=rename&metric=' + this.metric + '&newname=' + this.metricRename)
        .then((res) => {
          if (res.status == 200) {
            // this.metricNameArr = res.data.data.metricname
            console.log('重命名成功')
            this.$message('重命名成功!')
            this.getMetricTagTree() // 更新MetricTagTree
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('重命名失败!' + error)
        })
    },
    delmetric() {
      axiosservice.get('/buildmetrictagstree?method=delete&metric=' + this.metric)
        .then((res) => {
          if (res.status == 200) {
            // this.metricNameArr = res.data.data.metricname
            console.log('删除成功')
            this.$message('删除成功!')
            this.getMetricTagTree() // 更新MetricTagTree
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('重命名失败!' + error)
        })
    },
    submitAdd() {
      let tagsStr = '&tags='
      const tagslist = []
      for (const tag of this.metricForm.taglist) {
        console.log(1, tag)
        if (tag.tagname) {
          if (tag.tagvaluelist.length == 0) {
            this.$message.error('标签至少要有一个值')
          } else {
            for (const tagvalue of tag.tagvaluelist) {
              tagsStr = tagsStr + tag.tagname + ':' + tagvalue + ','
              tagslist.push(tag.tagname + ':' + tagvalue)
            }
          }
        }
      }
      console.log(2, tagsStr.slice(0, tagsStr.length - 1))
      tagsStr = tagsStr.slice(0, tagsStr.length - 1)
      // this.addmetric(tagsStr)
      this.addmetric(tagslist)
    }
  }
}
</script>

<style scoped>
@charset "UTF-8";
.formCol{
  height: 40px;
  line-height: 40px;
/* background-color:#e8e8e8; */
}
.tagLabel{
  padding-left: 10px;
  text-align: left;
  float:left;
}
label{
  font-size: 14px
}
.tagSelect2{
  width: 100px;

}
.tagDiv2{
  height: 40px;
  line-height: 40px;
  float:left;
  margin-right: 10px;
}

</style>
